﻿using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using HTTP = System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Reborn.Net.Http.Extension;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System.Net.Http;

namespace Reborn.Net.Http.Drive
{
    public class HttpClientDrive : Drive
    {
        HttpClientHandler _httpClientHandler = null;
        HTTP.HttpClient _httpClient = null;
        CookieContainer _cookies = new CookieContainer();

        public HttpClientDrive(HttpConfig httpConfig) : base(httpConfig)
        {
            _httpClientHandler = new HttpClientHandler();
            _httpClientHandler.CookieContainer = _cookies;
            _httpClientHandler.UseCookies = false;
            _httpClient = new HTTP.HttpClient(_httpClientHandler);

            Timeout = 180 * 1000;
        }

        /// <summary>
        /// 设置头信息
        /// </summary>
        /// <param name="httpContent"></param>
        /// <param name="request"></param>
        void SetRequest(HttpContent httpContent, Request request = null)
        {
            if (request == null) return;

            //替换头信息
            if (!string.IsNullOrEmpty(request.HeaderString))
            {
                string[] strings = request.HeaderString.Replace("\r","").Split('\n');
                foreach (var item in strings)
                {
                    if (string.IsNullOrEmpty(item)) continue;
                    int index = item.IndexOf(':');
                    if (index == -1) continue;

                    string name = item.Substring(0, index).Trim();
                    string value = item.Substring(index + 1);

                    if (request.Headers.ContainsKey(name)) continue;

                    request.Headers.Add(name, value.Trim());

                }
            }


            foreach (KeyValuePair<string, string> item in request.Headers)
            {
                string checkItemKey = item.Key.ToLower().Replace("-", "").Trim();
                if (checkItemKey == "useragent")
                {
                    _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("user-agent", item.Value);
                }
                if (checkItemKey == "accept")
                {
                    _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", item.Value);
                }
                if (checkItemKey == "authorization")
                {
                    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(item.Value);
                }
                else
                {
                    httpContent.Headers.TryAddWithoutValidation(item.Key, item.Value);
                }
            }
        }

        public override Response Get(string url, Request request = null)
        {
            return _httpClient.TryGetAsync(url).Result;
        }

        public override Task<Response> GetAsync(string url, Request request = null)
        {
            return _httpClient.TryGetAsync(url);
        }

        public override Response Post(string url, string token, Request request = null)
        {
            HttpContent content = new StringContent(token);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
            SetRequest(content, request);

            return _httpClient.TryPostAsync(url, content).Result;
        }

        public override Task<Response> PostAsync(string url, string token, Request request = null)
        {
            HttpContent content = new StringContent(token);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
            SetRequest(content, request);

            return _httpClient.TryPostAsync(url, content);
        }

        public override Response PostJson(string url, JToken postArgs, Request request = null)
        {
            string postStr = JsonToString(postArgs);

            HttpContent content = new StringContent(postStr);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            SetRequest(content, request);

            return _httpClient.TryPostAsync(url, content).Result;
        }

        public override Task<Response> PostJsonAsync(string url, JToken postArgs, Request request = null)
        {
            string postStr = JsonToString(postArgs);

            HttpContent content = new StringContent(postStr);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            SetRequest(content, request);


            return _httpClient.TryPostAsync(url, content);
        }

        public override Response Post(string url, Dictionary<string, string> dicArgs, Request request = null)
        {
            string postStr = DictionaryToString(dicArgs);

            return Post(url, postStr, request);
        }

        public override Task<Response> PostAsync(string url, Dictionary<string, string> dicArgs, Request request = null)
        {
            string postStr = DictionaryToString(dicArgs);

            return PostAsync(url, postStr, request);
        }

        public override byte[] GetByte(string url)
        {
            return _httpClient.GetByteArrayAsync(url).Result;
        }

        public override Task<byte[]> GetByteAsync(string url)
        {
            return _httpClient.GetByteArrayAsync(url);
        }
    }
}
